// pages/user/user.js
var app = getApp();

let JMessage = require('../../utils/jmessage-wxapplet-sdk-1.4.0.min.js');
let utilMd5 = require('../../utils/md5.js');
let fetch = require('../../utils/fetch');

let JIM = new JMessage({
  debug: true
});
let myDate = new Date().getTime();
let signature = utilMd5.hexMD5("appkey=00ca9e9d16207e781db439b4&timestamp=" + myDate + "&random_str=abcdefghijk_123456789&key=83e09cf66db6e3b1f69366d3");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //医生列表
    experts: [],
    mine: [],
    tabArr: {
      curHdIndex: '1',
      curBdIndex: '1'
    },
    //用户列表
    waitingList: [],
    doctorTabArr: {
      curHdIndex: '1',
      curBdIndex: '1'
    },
    tabNumber: {
      one: 0,
      two: 0,
      three: 0
    },
    //对话框内容
    userMsg: [],
    inputMsg: "",
    userId: "",
    userStatus: "",
    showImgAddBox: true,
    showDialogue: true,
    showDoctorList: true,
    showUserList: true,
    allTempFilePaths: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    wx.showLoading({
      title: '加载中',
      mask: true
    });

    const that = this;

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          dialogueHeight: res.windowHeight
        })
      },
    })


    //判断角色
    if (app.loginUser.role == "2") {
      this.showNowBox(true, false, true)
    } else {
      //医生列表-用户列表-对话框
      this.showNowBox(false, true, true)
      //医生列表
      fetch('inquiryDoctor/doctor/list').then(res => {
        this.setData({
          experts: res.data.data
        });

      });

    }


    //获取登录的用户判定是否注册极光JIM isOrRegister  1是注册 0是未注册
    fetch("inquiryDoctor/" + app.loginUser.id + '/isOrRegister').then(res => {
      app.userIMinfo = res.data.data;
      if (!res.data.data.isOrRegister) {
        this.initJim().then(x => {
          fetch('inquiryDoctor/saveImInformation', {
            'userId': app.loginUser.id
          }, 'POST').then(res => {})
          //未注册进行极光账号注册
          JIM.register({
            'username': res.data.data.imUsername,
            'nickname': app.loginUser.nickName,
            'password': res.data.data.imPassword,
            'is_md5': true
          }).onSuccess(function (data) {

            //start ------  JIM注册后登录
            JIM.login({
              'username': res.data.data.imUsername,
              'password': res.data.data.imPassword,
              'is_md5': true
            }).onSuccess(data => {
              wx.hideLoading();

              //监听实时会话信息
              JIM.onMsgReceive(function (data) {
                console.log("实时消息")
                console.log(data.messages)
                if (data.messages.length > 0) {
                  that.setMsgBox(that.data.userId, data.messages);
                }
              });

              //监听离线新消息
              JIM.onSyncConversation(function (data) {
                console.log("离线消息")
                console.log(data.messages)
                if (data.length >= 1) {
                  for (let i = 0; i < data.length; i++) {
                    if (that.data.userId == data[i].from_username) {
                      for (let j = 0; j < data[i].msgs.length; j++) {
                        that.setMsgBox(that.data.userId, data[i].msgs[j]);
                      }
                    }
                  }
                }
              });

              //获取极光用户列表
              JIM.getConversation().onSuccess(function (data) {

                if (app.loginUser.role == "2") {
                  wx.hideLoading();
                  const statusNumber = {}
                  statusNumber.one = 0
                  statusNumber.two = 0
                  statusNumber.three = 0
                  for (let i = 0; i < data.conversations.length; i++) {
                    var count = JIM.getUnreadMsgCnt({
                      'username': data.conversations[i].username
                    });
                    data.conversations[i].mtime = app.modTime(data.conversations[i].mtime, "yyyy.mm.dd HH:mm:ss");
                    data.conversations[i].count = count;

                    fetch("inquiryDoctor/query/inquiryStatus?userImName=" + data.conversations[i].username + "&doctorImName=" + app.userIMinfo.imUsername).then(res => {
                      data.conversations[i].status = res.data.data.status
                      if (data.conversations[i].status == '1') {
                        statusNumber.one += 1
                      } else if (data.conversations[i].status == '2') {
                        statusNumber.two += 1
                      } else {
                        statusNumber.three += 1
                      }
                      that.setData({
                        waitingList: data.conversations,
                        tabNumber: statusNumber
                      })
                    })
                  }
                } else {
                  wx.hideLoading();
                  fetch("inquiryDoctor/" + app.loginUser.id + '/isOrRegister').then(res => {})
                  for (let i = 0; i < data.conversations.length; i++) {
                    const doctorId = data.conversations[i].username.match(/\d+/g);
                    fetch("inquiryDoctor/" + doctorId + '/isOrRegister').then(res => {
                      data.conversations[i].department = res.data.data.department
                      data.conversations[i].description = res.data.data.description
                      data.conversations[i].doctorTitle = res.data.data.doctorTitle
                      data.conversations[i].hospital = res.data.data.hospital
                      that.setData({
                        mine: data.conversations
                      })
                    })
                  }
                }


              }).onFail(function (data) {
                wx.showToast({
                  title: '请求超时',
                  icon: 'fail',
                  duration: 1500
                })
              });
              //获取极光列表 end
            }).onFail(data => {
              console.log(data)
            })
            //end  ------- JIM注册后登录
          }).onFail(function (data) {
            wx.showToast({
              title: '请求超时',
              icon: 'fail',
              duration: 1500
            })
          });
        })

      } else {
        wx.showLoading({
          title: '加载中',
          mask: true
        });

        //start  ----- JIM已经注册直接登录
        this.initJim().then(x => {
          JIM.login({
            'username': res.data.data.imUsername,
            'password': res.data.data.imPassword,
            'is_md5': true
          }).onSuccess(data => {
            wx.hideLoading();

            //监听实时会话信息
            JIM.onMsgReceive(function (data) {
              console.log("实时消息")
              console.log(data.messages)
              if (data.messages.length > 0) {
                that.setMsgBox(that.data.userId, data.messages);
              }
            });

            //监听离线新消息
            JIM.onSyncConversation(function (data) {
              console.log("离线消息")
              console.log(data.messages)
              if (data.length >= 1) {
                for (let i = 0; i < data.length; i++) {
                  if (that.data.userId == data[i].from_username) {
                    for (let j = 0; j < data[i].msgs.length; j++) {
                      that.setMsgBox(that.data.userId, data[i].msgs[j]);
                    }
                  }
                }
              }
            });

            //获取极光列表 start
            JIM.getConversation().onSuccess(function (data) {
              wx.hideLoading();
              fetch("inquiryDoctor/" + app.loginUser.id + '/isOrRegister').then(res => {})
              for (let i = 0; i < data.conversations.length; i++) {
                const doctorId = data.conversations[i].username.match(/\d+/g);
                fetch("inquiryDoctor/" + doctorId + '/isOrRegister').then(res => {
                  data.conversations[i].department = res.data.data.department
                  data.conversations[i].description = res.data.data.description
                  data.conversations[i].doctorTitle = res.data.data.doctorTitle
                  data.conversations[i].hospital = res.data.data.hospital
                  that.setData({
                    mine: data.conversations
                  })
                })
              }
            }).onFail(function (data) {
              wx.showToast({
                title: '请求超时',
                icon: 'fail',
                duration: 1500
              })
            });
            //获取极光列表 end

          }).onFail(data => {
            console.log(data)
          })
        })
        //end   -------  JIM已经注册直接登录
      }
    });

  },

  //初始化极光
  initJim() {
    return new Promise((resolve, reject) => {
      JIM.init({
        "appkey": "00ca9e9d16207e781db439b4",
        "random_str": "abcdefghijk_123456789",
        "signature": signature,
        "timestamp": myDate
      }).onSuccess(function (data) {
        resolve(data)
      })
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  //选择显示当前页面
  showNowBox(j, k, l) {
    this.setData({
      showDoctorList: j,
      showUserList: k,
      showDialogue: l
    })
  },

  //医生端tab
  doctorTopTab: function (e) {
    var dataId = e.currentTarget.id;
    var obj = {};
    obj.curHdIndex = dataId;
    obj.curBdIndex = dataId;
    this.setData({
      doctorTabArr: obj
    })
  },

  //用户端tab
  topTab: function (e) {
    var dataId = e.currentTarget.id;
    var obj = {};
    obj.curHdIndex = dataId;
    obj.curBdIndex = dataId;
    this.setData({
      tabArr: obj
    })
  },

  
  goNext: function (e) {
    wx.navigateTo({
      url: '../doctor/doctor?id=' + e.currentTarget.id
    })
  },
  //初始化对话
  tellAnyOne: function (e) {
    wx.hideTabBar({
      animation: true //是否需要过渡动画
    })
    //显示对话框
    this.showNowBox(true, true, false)

    const that = this;

    this.setData({
      userMsg: "",
    })

    //调出本地储存的消息
    wx.getStorage({
      key: e.currentTarget.id,
      success: function (res) {
        that.setData({
          userMsg: res.data,
        })
      }
    })

    //设置信息
    this.setData({
      userId: e.currentTarget.id
    })

  },
  closeDialogue: function () {
    wx.showTabBar({
      animation: true //是否需要过渡动画
    })

    this.setData({
      userMsg: "",
    })
    //显示用户端列表
    this.showNowBox(false, true, true);

  },

  //随机匹配医生
  systemDoc: function () {
    var Range = this.data.experts.length;
    var Rand = Math.random();
    if (Math.round(Rand * Range) == 0) {
      return 1;
    }
    var numId = Math.round(Rand * Range);
    wx.navigateTo({
      url: '../doctor/doctor?id=' + numId
    })
  },

  showImgBox: function () {
    let showBox = !this.data.showImgAddBox;
    this.setData({
      showImgAddBox: showBox
    })
  },

  //发送消息
  submitMsg: function () {
    if (this.data.inputMsg) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });

      const that = this;
      //发送消息
      JIM.sendSingleMsg({
        'target_username': that.data.userId,
        'content': that.data.inputMsg,
        no_offline: false
      }).onSuccess(function (data, msg) {
        let sendMsg = [{
          "content": {
            "msg_body": {},
            "create_time": "",
            "toMsg": true
          }
        }];
        sendMsg[0].content.msg_body.text = that.data.inputMsg;
        sendMsg[0].content.create_time = myDate;

        //放入消息盒子
        that.setMsgBox(that.data.userId, sendMsg);
        wx.hideLoading();
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 1500
        })

        //清空input
        that.setData({
          inputMsg: ''
        })

        //医生端回复
        if (app.loginUser.role == "2") {
          const replyData = {};
          replyData.userImName = that.data.userId;
          replyData.doctorImName = app.userIMinfo.imUsername;
          fetch("/inquiryDoctor/Messages/replyTime", replyData, "POST").then(res => {});
        }

      }).onFail(function (data) {
        wx.showToast({
          title: '发送失败',
          icon: 'fail',
          duration: 1500
        })
      });

    }
  },

  // 获取input内部消息
  takeMsg: function (e) {
    this.setData({
      inputMsg: e.detail.value
    })
  },

  //保存用户收发信息
  setMsgBox: function (id, item) {
    const that = this;
    //把新信息添加到userMsg里
    let msgBox = that.data.userMsg

    for (let i = 0; i < item.length; i++) {
      item[i].content.create_time = app.modTime(item[i].content.create_time, "yyyy.mm.dd HH:mm:ss");
    }

    if (msgBox.length > 0) {
      msgBox = msgBox.concat(item)
    } else {
      msgBox = item
    }

    //保存消息
    that.setData({
      userMsg: msgBox
    })

    console.log(that.data.userMsg)
    console.log(id)
    //把新得到的msgBos存到本地缓存
    wx.setStorage({
      key: id,
      data: msgBox
    })
  },
})